﻿
using AutoMapper;
using D.Traceability.Domain;
using D.Traceability.ErrorCode;
using D.Traceability.Infrastructure.Infrastructure;
using D.Traceability.Write.API.APPlicant.Command;
using D.Traceability.Write.API.APPlicant.Command.BreedCommand;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace D.Traceability.Write.API.APPlicant.CommandHandler.BreedCommandHandler
{
    /// <summary>
    ///  添加保健信息
    /// </summary>
    public class AddImmunityCommandHandler : IRequestHandler<AddImmunityCommand, APIResult<string>>
    {
        private readonly IBaseRepository<SU_ImmunityModel> baseRepository;
        private readonly IMapper mapper;

        public AddImmunityCommandHandler(IBaseRepository<SU_ImmunityModel> baseRepository, IMapper mapper)
        {
            this.baseRepository = baseRepository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 添加保健信息
        /// </summary>
        public async Task<APIResult<string>> Handle(AddImmunityCommand request, CancellationToken cancellationToken)
        {
            APIResult<string> result = new APIResult<string>();

            //查询是否含有数据(通过 生产批次 TraceaBatch查询)
            //var obj = await baseRepository.GetAll().Result.FirstOrDefaultAsync(x => x.TraceaBatch == request.TraceaBatch && x.TraceaIsDelete == false);
            //有数据执行修改操作
            //if (obj != null)
            //{
            //    obj.BreedVariety = request.BreedVariety;
            //    obj.BreedSource = request.BreedSource;
            //    obj.BreedDay = request.BreedDay;
            //    obj.BreedBrand = request.BreedBrand;
            //    obj.BreedOPeratorName = request.BreedOPeratorName;
            //    obj.BreedCrateTime = request.BreedCrateTime.Value.AddHours(8);
            //    int res = await baseRepository.Update(obj);
            //    if (res > 0)
            //    {
            //        result.Code = APIEnum.设置成功;
            //        result.Msg = APIEnum.设置成功.ToString();
            //        result.data = res.ToString();
            //    }
            //    else
            //    {
            //        result.Code = APIEnum.设置失败;
            //        result.Msg = APIEnum.设置失败.ToString();
            //        result.data = res.ToString();
            //    }
            //}
            //else
            //{
            //添加操作
            var model = mapper.Map<SU_ImmunityModel>(request);
            int res = await baseRepository.Add(model);
            if (res > 0)
            {
                result.Code = APIEnum.添加成功;
                result.Msg = APIEnum.添加成功.ToString();
                result.data = res.ToString();
            }
            else
            {
                result.Code = APIEnum.添加失败;
                result.Msg = APIEnum.添加失败.ToString();
                result.data = res.ToString();
            }
            //}
            return await Task.FromResult(result);
        }
    }
}
